"""
    @author yu_chen
    @date  2019年09月21日18:37:47
    @todo
"""
import requests
from lxml import etree

from spider_common.FileUtil import FileUtil
from spider_common.Proxy import Proxy


class GetSongs(object):
    def __init__(self):
        self.headers = {
            'Referer': 'http://music.163.com/',
            'Host': 'music.163.com',
            'Accept-Language': "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3",
            'Accept-Encoding': "gzip, deflate",
            'Content-Type': "application/x-www-form-urlencoded",
            'Origin': 'https://music.163.com',
            'Connection': "keep-alive",
            'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36'
                          ' (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'
        }
        # 构造会话
        self.session = requests.session()
        # 设置代理
        self.proxy = Proxy()
        self.download_url = "http://music.163.com/song/media/outer/url?id=%s.mp3"

    def send_request(self, url):
        """
        发送http请求
        :param url:请求的url
        :return:
        """
        try:
            # response = self.session.get(url, headers=self.headers)
            response = self.session.get(url, headers=self.headers, proxies=self.get_proxy())
        except:
            self.get_proxy()
            response = self.session.get(url, headers=self.headers, proxies=self.get_proxy())
        return response

    def get_proxy(self):
        # 设置代理
        self.proxies = {
            'https': self.proxy.get_proxy_url()
        }
        return self.proxies

    def get_songs_id(self, songs_list_name, url):
        """
        :param url: 主页链接
        :song_list_id url: 歌单的ID
        :return: 所有歌曲名字，id
        """
        html = self.send_request(url)
        text = etree.HTML(html.text)
        songs_name = text.xpath('//div[@id="song-list-pre-cache"]//ul//a/text()')
        # 获取歌曲id
        songs_id = text.xpath('//div[@id="song-list-pre-cache"]//ul//a/@href')
        songs_id = [s_id[9:] for s_id in songs_id]
        print(songs_name)
        print(songs_id)
        for i in range(len(songs_name)):
            FileUtil.download_mp3(self.download_url % songs_id[i],
                                  '../spider_resource/mp3/%s/%s.mp3' % (songs_list_name, songs_name[i]))


if __name__ == '__main__':
    singer_url = 'https://music.163.com/playlist?id=2748205282'  # 记得要去掉#号，太那啥了
    spider = GetSongs()
    spider.get_songs_id('解忧老樊 解忧邵帅', singer_url)
